<template>
  <div class="order">
    <div class="header">
      <div class="left">订单列表</div>
      <img src="@/assets/img/fork.svg" class="right" @click="orderCancel" />
    </div>
    <van-pull-refresh v-model="loading" @refresh="getList" class="list">
      <div class="rows" v-for="(rows, index) in orderList" :key="index">
        <div class="row" v-for="item in rows" :key="item.baseOrderNo">
          <img
            :src="item.actorCapture"
            class="img"
            @click="previewActorAcpture(item.actorCapture)"
          />
          <div class="msg" @click="orderClick(item)">
            <div class="title">
              <div class="no" @click.stop="toDetail(item)">
                {{ item.baseOrderNo || '' }}
                <img
                  src="@/assets/img/qr-code.svg"
                  v-show="item.extend3 === 'ytj' && item.weightType === '1'"
                  class="type-img"
                />
                <img
                  src="@/assets/img/face.svg"
                  v-show="item.extend3 === 'ytj' && item.weightType === '2'"
                  class="type-img"
                />
                <img
                  src="@/assets/img/id-card.svg"
                  v-show="item.extend3 === 'ytj' && item.weightType === '3'"
                  class="type-img"
                />
                <img src="@/assets/img/app.svg" v-show="item.extend3 === 'app'" class="type-img" />
                <img src="@/assets/img/xcx.svg" v-show="item.extend3 === 'xcx'" class="type-img" />
              </div>
              <div
                class="status"
                :style="{ color: item.processColor }"
                @click.stop="changeMarker(item)"
              >
                {{ item.processName }}
              </div>
            </div>
            <div class="middle">
              <div class="weight">
                <div class="child" v-if="item.weightIn !== null">
                  初磅重量:
                  <div class="number">{{ saveWeightToShow(item.weightIn) }}</div>
                  {{ weightUnit }}
                </div>
                <div class="child" v-if="item.weightOut !== null">
                  {{ numberToChinese(item.weightLength + 1) }}磅重量:
                  <div class="number">{{ saveWeightToShow(item.weightOut) }}</div>
                  {{ weightUnit }}
                </div>
                <div class="child" v-else></div>
              </div>
              <div class="price-container" v-if="Number(item.process) > 2">
                <div class="child impurity">
                  <div class="label">扣杂：</div>
                  <div class="value">
                    {{ saveWeightToShow(item.inspectImpurity) }}{{ weightUnit }}
                  </div>
                </div>
                <div class="child price">
                  <div class="label">单价：</div>
                  <div class="value">
                    {{ savePriceToShow(item.priceTaxOut) }} 元/{{ weightUnit }}
                  </div>
                </div>
                <div class="child price-total">
                  <div class="label">总价：</div>
                  <div class="value">{{ item.totalAmountTaxOut }}元</div>
                </div>
              </div>
            </div>
            <div class="footer">
              <div class="left">
                <div class="cus">
                  {{ item.flow === '1' ? item.supplierName : item.customerName }}
                </div>
                <div class="number" v-if="item.number">{{ item.number }}</div>
              </div>

              <div class="right">
                {{ item.createTime }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="orderList.length === 0" class="no-text">暂无数据</div>
    </van-pull-refresh>
  </div>
  <van-action-sheet
    cancel-text="取消"
    v-model:show="orderActionShow"
    :actions="orderActions"
    @select="onOrderActionSelect"
  />

  <van-action-sheet
    v-model:show="markerActionShow"
    :actions="markerActions"
    @select="onMarkerActionSelect"
  />
</template>

<script setup>
import api from '@/api/index'
import {
  getDayStart,
  getDayEnd,
  formatNumber,
  numberToChinese,
  getColorFromChar
} from '@/libs/utils'
import { getCodeValueAndColor, getCode } from '@/libs/code'
import { ref, onMounted } from 'vue'
import { showNotify, showImagePreview } from 'vant'
import { useRouter } from 'vue-router'
import { getWeightUnit, saveWeightToShow, savePriceToShow } from '@/libs/unit'
const screenMode = window.innerWidth <= 1080 ? 1 : 2
const weightUnit = getWeightUnit()
const orderActionShow = ref(false)
const orderActions = [
  {
    id: '1',
    name: '标记收/付款'
  }
]
const searchForm = {
  flow: '',
  startDate: '',
  endDate: '',
  pageInfo: {
    pageSize: 100,
    pageNum: 1
  }
}
const loading = ref(false)
const orderList = ref([])
const getList = () => {
  searchForm.startDate = getDayStart(new Date())
  searchForm.endDate = getDayEnd(new Date())
  orderList.value = []

  const canvas = document.createElement('canvas')
  canvas.width = 70
  canvas.height = 102
  const ctx = canvas.getContext('2d')

  orderList.value = []
  let tempArr = []
  api
    .baseOrderList(searchForm)
    .then(async (res) => {
      for (const item of res.data) {
        if (item.flow === '' || item.flow === null) {
          item.processName = '待质检/装货'
          item.processColor = ' #f59a23'
        } else {
          let code = '',
            value = ''
          if (item.marker === '6') {
            if (item.status !== '1') {
              code = 'BASE_ORDER_CONFIRM_STATUS'
              value = item.status
            } else {
              code = item.flow === '1' ? 'BASE_ORDER_IN_PROCESS' : 'BASE_ORDER_OUT_PROCESS'
              value = item.process
            }
          } else {
            code = 'REMARK_TYPE'
            value = item.marker
          }
          ;({ itemName: item.processName, itemColor: item.processColor } =
            await getCodeValueAndColor(code, value))
        }
        if (item.materialInfo && item.materialInfo.length > 0) {
          item.materialName = item.materialInfo[0].materialName
        } else {
          item.materialName = ''
        }
        const date = new Date(item.createDate.split('-').join('/'))

        item.createTime = `${formatNumber(date.getMonth() + 1)}-${formatNumber(
          date.getDate()
        )} ${formatNumber(date.getHours())}:${formatNumber(date.getMinutes())}`
        item.actorCapture = null
        const weightPics = item.weightOutPics || item.weightInPics
        if (weightPics) {
          const weightPicsArr = weightPics.split(',')
          if (weightPicsArr[2]) {
            item.actorCapture = import.meta.env.VITE_FILE_DOMAIN + weightPicsArr[2]
          }
        }
        if (!item.actorCapture) {
          const cusName = item.flow === '1' ? item.supplierName : item.customerName
          const text = cusName[0]
          ctx.fillStyle = getColorFromChar(text)
          ctx.fillRect(0, 0, canvas.width, canvas.height)

          const fontSize = canvas.height * 0.5
          ctx.font = `${fontSize}px Arial` // 使用Arial字体，或者可以更改为其他字体
          ctx.fillStyle = '#ffffff'
          ctx.textBaseline = 'middle'
          const textMetrics = ctx.measureText(text)
          const textWidth = textMetrics.width
          const x = (canvas.width - textWidth) / 2
          const y = canvas.height / 2 + 5
          // 在画布上绘制文本
          ctx.fillText(text, x, y)
          item.actorCapture = canvas.toDataURL('image/png', 1)
        }
        item.weightType = item.weightOutType || item.weightInType
        if (item.priceTaxOut !== null) {
          item.priceTaxOut = Number(Number(item.priceTaxOut).toFixed(2))
        }
        if (item.totalAmountTaxOut !== null) {
          item.totalAmountTaxOut = Number(Number(item.totalAmountTaxOut).toFixed(2))
        } else {
          item.totalAmountTaxOut = '-'
        }
        if (item.inspectImpurity !== null) {
          item.inspectImpurity = Number(Number(item.inspectImpurity).toFixed(5))
        }
        if (item.materialInfo) {
          item.weightLength = item.materialInfo.length
        }
        tempArr.push(item)
        if (screenMode === 1) {
          orderList.value.push(tempArr)
          tempArr = []
        }
        if (screenMode === 2 && tempArr.length === 2) {
          orderList.value.push(tempArr)
          tempArr = []
        }
      }

      if (tempArr.length > 0) {
        orderList.value.push(tempArr)
        tempArr = []
      }
    })
    .finally(() => {
      loading.value = false
    })
}
const markerActionShow = ref(false)
const markerActions = ref([])
onMounted(() => {
  getList()
  getCode('REMARK_TYPE').then((codeArr) => {
    markerActions.value = codeArr.map((item) => ({
      name: item.itemName,
      id: item.itemValue
    }))
  })
})

let checkedOrder = null
const orderClick = (item) => {
  checkedOrder = item
  orderActionShow.value = true
}

const onOrderActionSelect = (e) => {
  orderActionShow.value = false
  switch (e.id) {
    case '1':
      markerActionShow.value = true
      break
  }
}
function changeMarker(item) {
  checkedOrder = item
  markerActionShow.value = true
}
const onMarkerActionSelect = (e) => {
  markerActionShow.value = false
  api.updateBaseOrderMarker({ id: checkedOrder.id, marker: e.id }).then(() => {
    showNotify({ type: 'success', message: '操作成功' })
    getList()
  })
}

const router = useRouter()
function toDetail(item) {
  router.push({
    path: '/OrderDetail',
    query: {
      id: item.id
    }
  })
}
function orderCancel() {
  window.android.orderCancel()
}
function previewActorAcpture(url) {
  showImagePreview({
    images: [url],
    closeable: true,
    startPosition: 0
  })
}
</script>

<style lang="scss" scope>
@import url('@/assets/style/mixins.scss');
@media screen and (max-width: 1080px) {
  .order {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    .list {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: stretch;
      overflow-y: auto;
      .no-text {
        font-size: 40px;
        color: #999;
        text-align: center;
        margin-top: 200px;
      }
      .row {
        display: flex;
        flex-direction: row;
        padding: 0.25rem 0.1rem;
        border-bottom: 1px solid #eeeeee;
        .img {
          width: 70px;
          height: 102px;
          margin-right: 0.2rem;
          border-radius: 2px;
        }
        .msg {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          flex: 1;
          width: 0;
          .title {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            font-size: 12px;
            align-items: center;
            .no {
              color: #02a7f0;
              display: flex;
              flex-direction: row;
              align-items: center;
              .type-img {
                width: 14px;
                height: 14px;
                margin-left: 8px;
              }
            }
            .status {
              font-weight: bold;
            }
          }
          .middle {
            display: flex;
            flex-direction: column;
            .weight {
              display: flex;
              flex-direction: row;
              align-items: center;
              font-size: 12px;
              .child {
                flex: 1;
                display: flex;
                flex-direction: row;
                justify-content: center;
                align-items: flex-end;
                height: 100%;
                .number {
                  font-weight: bold;
                  font-size: 20px;
                }
              }
            }
            .price-container {
              display: flex;
              flex-direction: row;
              align-items: center;
              font-size: 11px;
              margin-top: 8px;
              .child {
                display: flex;
                flex-direction: row;
                justify-content: center;
              }
              .impurity {
                width: 85px;
              }
              .price,
              .price-total {
                flex: 1;
              }
            }
          }
          .footer {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            font-size: 11px;
            height: 20px;
            .left {
              display: flex;
              flex-direction: row;
              height: 100%;
              .number {
                width: 70px;
                background-color: #44ed5f;
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: center;
                border-radius: 2px;
                height: 100%;
              }
              .cus {
                padding: 0 12px;
                display: flex;
                flex-direction: row;
                align-items: center;
                // justify-content: center;
                height: 100%;
                width: 132px;
                text-align: center;
              }
            }
          }
        }
      }
    }
  }
}
@media screen and (min-width: 1920px) {
  .order {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    .list {
      flex: 1;
      display: flex;
      flex-direction: row;
      align-items: stretch;
      .van-pull-refresh__track {
        width: 100%;
        overflow-y: auto;
      }
      .no-text {
        font-size: 40px;
        color: #999;
        text-align: center;
        margin-top: 200px;
      }
      .rows {
        display: flex;
        flex-direction: row;
        width: 100%;
      }
      .row {
        display: flex;
        flex-direction: row;
        border-bottom: 0.5px solid #eeeeee;
        border-right: 0.5px solid #eeeeee;
        width: calc(50% - 1px);
        .img {
          width: 40px;
          height: 48px;
          border-radius: 2px;
          margin: 1px;
        }
        .msg {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          flex: 1;
          width: 0;
          .title {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            font-size: 7px;
            align-items: center;
            margin-top: 2px;
            .no {
              color: #02a7f0;
              display: flex;
              flex-direction: row;
              align-items: center;
              .type-img {
                width: 6px;
                height: 6px;
                margin-left: 4px;
              }
            }
            .status {
              font-weight: bold;
              margin-right: 4px;
            }
          }
          .middle {
            display: flex;
            flex-direction: column;
            .weight {
              display: flex;
              flex-direction: row;
              align-items: center;
              font-size: 5px;
              .child {
                flex: 1;
                display: flex;
                flex-direction: row;
                justify-content: center;
                align-items: flex-end;
                height: 100%;
                .number {
                  font-weight: bold;
                  font-size: 9px;
                }
              }
            }
            .price-container {
              display: flex;
              flex-direction: row;
              align-items: center;
              font-size: 5px;
              margin-top: 2px;
              .child {
                display: flex;
                flex-direction: row;
                justify-content: center;
              }
              .impurity {
                width: 38px;
              }
              .price,
              .price-total {
                flex: 1;
              }
            }
          }
          .footer {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            font-size: 5px;
            height: 10px;
            margin-bottom: 2px;
            .left {
              display: flex;
              flex-direction: row;
              height: 100%;
              flex: 1;
              .number {
                width: 34px;
                background-color: #44ed5f;
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: center;
                border-radius: 2px;
                height: 100%;
              }
              .cus {
                display: flex;
                flex-direction: row;
                align-items: center;
                // justify-content: center;
                height: 100%;
                width: 54px;
                text-align: center;
              }
            }
            .right {
              margin-right: 4px;
            }
          }
        }
      }
    }
  }
}
</style>
